package com.zhuangwei.spring.hook.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器
 *  测试
 *  返回头不会包含CORS相关： curl -i ''http://127.0.0.1:8080/welcome?name=一灰灰' -e 'http://hhui.top'
 *  返回头支持CORS： curl -i 'http://127.0.0.1:8080/hello?name=一灰灰' -e 'http://hhui.top'
 *
 * @author 文希
 * @create 2019-05-23 17:36
 **/
public class MyCorsFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       try {
           HttpServletRequest req = (HttpServletRequest) request;
           HttpServletResponse res = (HttpServletResponse) response;

           if ("/hello".contentEquals(req.getRequestURL())){
               res.setHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
               res.setHeader("Access-Control-Allow-Methods", "*");
               res.setHeader("Access-Control-Allow-Credentials", "true");
           }
       }finally {
           chain.doFilter(request,response);
       }

    }

    public void destroy() {

    }
}
